from operator import attrgetter

from convert import Conversion

class Unit:
    def __init__(self, name):
        self._name = name
        self._edges = []
        self._base_unit = None

    name = property(attrgetter("_name"))
    edges = property(lambda self: (e for e in self._edges))

    def add_edge(self, conversion):
        self._edges.append(conversion)

    def derive_unit(self, base_unit, from_expr, to_expr):
        if self._base_unit is not None:
            raise UnitException(u"Unit %s: to set base unit to %s, but already is %s" %
                                (self._name, base_unit, self._base_unit))
        elif base_unit is not None:
            self._base_unit = None
            base_unit.add_edge(Conversion(self, from_expr))
            self.add_edge(Conversion(base_unit, to_expr))

    def __str__(self):
        return u"<Unit %s>" % self._name
